package com.czy.lxtFX;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzy
 *  集合工具类
 * @since 2020-05-11
 */
public class ListUtil {
    public static boolean isEmpty(Object[] array) {
        return (array == null || array.length == 0);
    }
    public static <T> boolean isEmpty(List<T> list) {
        return list == null || list.isEmpty();
    }
    public static <T> boolean isEmpty(Set<T> list) {
        return list == null || list.isEmpty();
    }
    public static boolean isEmpty(Map<?,?> map) {
        return map == null || map.isEmpty();
    }
    public static <T> boolean isNotEmpty(List<T> list) {
        return !isEmpty(list);
    }
    public static <T> boolean isNotEmpty(Object[] list) {
        return !isEmpty(list);
    }
    public static boolean isEmptyOr(Object[]... array) {
        if (isEmpty(array)){
            return true;
        }
        return Arrays.stream(array).anyMatch(ListUtil::isEmpty);
    }
    public static boolean isEmptyOr(List... list) {
        if (isEmpty(list)){
            return true;
        }
        return Arrays.stream(list).anyMatch(ListUtil::isEmpty);
    }

    public static boolean isEmptyAnd(List... list) {
        if (isEmpty(list)){
            return true;
        }
        return Arrays.stream(list).allMatch(ListUtil::isEmpty);
    }
    /*交集*/
    public static<T> List<T> intersect(List<T> list1, List<T> list2){
        if (isEmptyOr(list1,list2)){
            return Collections.emptyList();
        }
        return list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
    }
    /*差集,list1-list2*/
    public static<T> List<T> except(List<T> list1, List<T> list2){
        if (isEmpty(list1)){
            return Collections.emptyList();
        }
        if (isEmpty(list2)){
            return list1;
        }
        return list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
    }
    /*去重并集*/
    public static<T> List<T> union(List<T> list1, List<T> list2){
        if (isEmptyAnd(list1,list2)){
            return Collections.emptyList();
        }
        if (isEmpty(list1)){
            return list2;
        }
        if (isEmpty(list2)){
            return list1;
        }
        list1.addAll(list2);
        return list1.stream().distinct().collect(Collectors.toList());
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] list2Array(List<T> list) {
        if (isEmpty(list)){
            return null;
        }
        T[] ts= (T[]) list.toArray();
        return ts;
    }
    /*创建泛型数组*/
    @SuppressWarnings("unchecked")
    public static<T> T[] newArray(Class<T> tClass, int length){
        return (T[]) Array.newInstance(tClass, length);
    }
}
